#include "TypeTestModule.h"

TypeTestModule::TypeTestModule()
{
    m_totalCnt = 0;
    m_correctCnt = 0;
    m_costTime = 0;
    memset(m_testContent, 0, sizeof(m_testContent));
    memset(m_inputContent, 0, sizeof(m_inputContent));
}


TypeTestModule::~TypeTestModule()
{
    if (m_fileObj.is_open()) {
        m_fileObj.close();
    }
}


void TypeTestModule::_recordResult() 
{
    int length = strlen(m_testContent);
    m_totalCnt += length;

    for (int i = 0; i < length; i++) {
        m_correctCnt += 
            (m_testContent[i]==m_inputContent[i]) ? 1 : 0;
    }
}


void TypeTestModule::_echoTestContent(void)
{
    memset(m_testContent, 0, sizeof(m_testContent));
    m_fileObj.getline(m_testContent, sizeof(m_testContent));
    std::cout << m_testContent << std::endl;
}


void TypeTestModule::_recvInputContent(void)
{
    time_t startTime = 0;
    time_t endTime = 0;
    memset(m_inputContent, 0, sizeof(m_inputContent));

    startTime = time(NULL);
    std::cin.getline(m_inputContent, sizeof(m_inputContent), '\n');
    endTime = time(NULL);

    m_costTime += (endTime - startTime);
}


void TypeTestModule::_calculateScore(TypeTestResult_t &result)
{
    result.accuracyRate = m_correctCnt*1.0 / m_totalCnt;
    result.costTime = m_costTime;
    // TO DO
    // result->totalScore 分数的计算方法暂时省略
}


// Author: zhang_cs
// date: 2022-4-24
// @path: 指定打字测试内容的文件路径
// @retVal: 0初始化成功，-1初始化失败
// PS: 如果需要更换测试文件，重新initial指定新文件路径即可
int TypeTestModule::initial(const char* path)
{
    if (!path) {
        std::cout  << " Input file path is NULL." << std::endl;
        return -1;
    }

    if (m_fileObj.is_open()) {
        m_fileObj.close();
    }

    m_fileObj.open(path, std::ios::in);
    if (!m_fileObj.is_open()) {
        std::cout << path << " file open failed." << std::endl;
        return -1;
    }

    return 0;
}


// Author: zhang_cs
// date: 2022-4-24
// description： 开启一次打字测试，支持重复调用进行多次测试
// @result: 存储本次测试结果
void TypeTestModule::startTypeTest(TypeTestResult_t &result)
{
    memset(&result, 0, sizeof(TypeTestResult_t));

    m_totalCnt = 0;
    m_correctCnt = 0;
    m_costTime = 0;
    m_fileObj.seekg(std::ios_base::beg);
    
    int i = 0;
    while (!m_fileObj.eof()) {
        std::cout << i++ << ": ";
        this->_echoTestContent();
        this->_recvInputContent();
        this->_recordResult();
    }
    this->_calculateScore(result);
}
